package com.mlethe.library.fingerprint.uitls;

import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;

import androidx.annotation.RequiresApi;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 * 加密类，用于判定指纹合法性
 */
@RequiresApi(Build.VERSION_CODES.M)
public class CipherHelper {

    private static CipherHelper instance;

    // This can be key name you want. Should be unique for the app.
    static final String KEYSTORE_ALIAS = "com.hailong.fingerprint.CipherHelper";

    // We always use this keystore on Android.
    static final String KEYSTORE_NAME = "AndroidKeyStore";

    // Should be no need to change these values.
    static final String KEY_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES;
    static final String BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC;
    static final String ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7;
    static final String TRANSFORMATION = KEY_ALGORITHM + "/" + BLOCK_MODE + "/" + ENCRYPTION_PADDING;

    private KeyStore keyStore;

    private KeyGenerator mKeyGenerator;

    private CipherHelper() {
        try {
            keyStore = KeyStore.getInstance(KEYSTORE_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE_NAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static CipherHelper getInstance() {
        if (instance == null) {
            synchronized (CipherHelper.class) {
                if (instance == null) {
                    instance = new CipherHelper();
                }
            }
        }
        return instance;
    }

    /**
     * @des 创建cipher
     */
    public Cipher createCipher() {
        try {
            return Cipher.getInstance(TRANSFORMATION);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @des 初始化Cipher ,根据KeyPermanentlyInvalidatedExceptiony异常判断指纹库是否发生了变化
     */
    public boolean initCipher(Cipher cipher) {
        try {
            keyStore.load(null);
            SecretKey key = (SecretKey) keyStore.getKey(KEYSTORE_ALIAS, null);
            if (cipher == null) {
                cipher = createCipher();
            }
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return false;
        } catch (KeyPermanentlyInvalidatedException | UnrecoverableKeyException e) {
            //指纹库是否发生了变化,这里会抛KeyPermanentlyInvalidatedException
            return true;
        } catch (KeyStoreException | CertificateException | IOException
                | NoSuchAlgorithmException | InvalidKeyException e) {
//            throw new RuntimeException("Failed to init Cipher", e);
            e.printStackTrace();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    /**
     * 创建新密钥
     *
     * @throws Exception
     */
    public void createKey() throws Exception {
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEYSTORE_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.setInvalidatedByBiometricEnrollment(true);
        }
        mKeyGenerator.init(builder.build());
        mKeyGenerator.generateKey();
    }
}